package com.stb.isharemessage.ui.feed;

//import com.allen.ui.profile.ProfileActivity;

import java.io.File;




import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;






























import cn.finalteam.galleryfinal.GalleryHelper;
import cn.finalteam.galleryfinal.GalleryImageLoader;
import cn.finalteam.galleryfinal.PhotoCropActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.BitmapUtils;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.Logger;

import com.speed.im.login.EncryptionUtil;
import com.spice.im.BaseActivity;
import com.spice.im.BaseDialog;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.ImageFactoryActivity;
import com.spice.im.R;
import com.spice.im.RoundImageView;
import com.spice.im.SpiceApplication;
import com.spice.im.group.MucCreateActivity;
import com.spice.im.group.MucCreateActivity.exPhoneCallListener;
import com.spice.im.preference.PreferenceActivity;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.Feed;
import com.spice.im.utils.ImageFetcher;
import com.spice.im.utils.PhotoUtils;
import com.stb.core.chat.ContactGroup;
//import com.allen.ui.profile.ProfileActivity.BeemServiceConnection;
//import com.allen.ui.profile.ProfileActivity;
//import com.stb.isharemessage.R;
//import com.stb.isharemessage.ui.AdvancedSearchResPullRefListActivity.OnRightImageButtonClickListener;
import com.stb.isharemessage.service.aidl.IXmppFacade;
//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.BeemService;
import com.stb.isharemessage.IConnectionStatusCallback;
//import com.stb.isharemessage.service.UserInfo;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.ui.feed.EmoteInputView;
import com.stb.isharemessage.ui.feed.EmoticonsEditText;
import com.stb.isharemessage.ui.feed.EmoticonsTextView;
import com.stb.isharemessage.ui.feed.FeedProfileActivity;
import com.stb.isharemessage.ui.feed.OtherFeedListActivity;
//import com.stb.isharemessage.ui.list.SelectPicPopupWindow;
//import com.stb.isharemessage.ui.list.BasePopupWindow.onSubmitClickListener;
//import com.stb.isharemessage.ui.register.BaseActivity;
//import com.stb.isharemessage.ui.register.BaseDialog;
//import com.stb.isharemessage.ui.register.FlippingLoadingDialog;
import com.stb.isharemessage.utils.BeemBroadcastReceiver;
import com.stb.isharemessage.utils.BeemConnectivity;
//import com.stb.isharemessage.utils.DateUtils;
//import com.stb.isharemessage.utils.FeedComment;
import com.stb.isharemessage.utils.FileUtils;
//import com.stb.isharemessage.utils.HeaderLayout;
//import com.stb.isharemessage.utils.PhotoUtils;
//import com.stb.isharemessage.utils.HeaderLayout.HeaderStyle;
//import com.stb.isharemessage.utils.HeaderLayout.onRightImageButtonClickListener;
//import com.tritrees.easygridview.widget.AllEasyGridView;
//import com.tritrees.easygridview.widget.EasyGridView;
//import com.tritrees.easygridview.widget.HeadImg;
//import com.tritrees.easygridview.widget.ImageAdapter;
//import com.tritrees.easygridview.widget.EasyGridView.IHandleGridView;











import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
//import com.stb.isharemessage.utils.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.PopupWindow.OnDismissListener;

public class AddDynamicsActivity extends Activity implements IConnectionStatusCallback,OnClickListener,OnTouchListener{//IHandleGridView
	
	private static final String TAG = AddDynamicsActivity.class.getSimpleName();
	
    private static final Intent SERVICE_INTENT = new Intent();
    static {
    	SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));//自身应用pkg名称，非service所在pkg名称
    }
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}
	private EmoticonsTextView mEtvEditerTitle;
//	private HandyTextView mEtvEditerTitle;
	private ImageView mIvEmote;
	private Button mBtnSend;
	private EmoticonsEditText mEetEditer;
	private EmoteInputView mInputView;
	
	private HeaderLayout mHeaderLayout;// 标题栏
	
	private HandyTextView user_item_htv_distance;
	
//	private SelectPicPopupWindow mPopupWindow;
//    private BaseDialog mBaseDialog;
//    public int mPosition;
//	EasyGridView allEasyGridView;
//	private ArrayList<HashMap<String, Object>> data;
//	private HashMap<String,Object> map;
	private RoundImageView mIvUserPhoto;
	private LinearLayout mLayoutSelectPhoto;
	private LinearLayout mLayoutTakePicture;
	private Bitmap mUserPhoto;
	public ImageFetcher mImageFetcher;
	
	
	
	private static final int CAMERA_WITH_DATA = 1;
	private static final int ICON_SIZE = 60;
	private static final int PHOTO_PICKED_WITH_DATA = 0;
	private static final String KEY_CURRENT_PHOTO_FILE = "currentphotofile";
	private IXmppFacade mXmppFacade;
	private boolean mBinded = false;
	private String jid;
//	private UserInfo ui;
	String CurrentUid = "";
	private final ServiceConnection mServConn = new BeemServiceConnection(this);
//	private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();//原来的网络状态注释掉
	private final OkListener mOkListener = new OkListener();
	@Override
	public void onBackPressed() {
		if (mInputView.isShown()) {
			mInputView.setVisibility(View.GONE);
		} else {
			finish();
		}
	}
	private Context mContext;
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_add_dynamics);
        
        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
        
		mEtvEditerTitle = (EmoticonsTextView) findViewById(R.id.feedprofile_etv_editertitle);
		mIvEmote = (ImageView) findViewById(R.id.feedprofile_iv_emote);
		mBtnSend = (Button) findViewById(R.id.feedprofile_btn_send);
		mEetEditer = (EmoticonsEditText) findViewById(R.id.feedprofile_eet_editer);
		mInputView = (EmoteInputView) findViewById(R.id.feedprofile_eiv_input);
		
		mHeaderLayout = (HeaderLayout) findViewById(R.id.otherprofile_header);
		mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.setTitleRightImageButton("发布动态", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
		user_item_htv_distance = (HandyTextView) findViewById(R.id.user_item_htv_distance);
		user_item_htv_distance.setText(SpiceApplication.getInstance().mGpsAddr);
//		this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));//原来的网络状态注释掉
		
//		mEetEditer.setOnTouchListener(this);
//		mBtnSend.setOnClickListener(this);
//		mIvEmote.setOnClickListener(this);
		mInputView.setEditText(mEetEditer);
		
	    mImageFetcher = new ImageFetcher(this, 240);
	    mImageFetcher.setUListype(0);
	    mImageFetcher.setLoadingImage(R.drawable.empty_photo);
	    mImageFetcher.setExitTasksEarly(false);
	    
//		initPopupWindow();
//		initData();
		initViews();
		initEvents();
		
        //网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(mOkListener);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
        SpiceApplication.getInstance().addActivity(this);
    }
    private String mtype = "";
    @Override
    protected void onResume() {
		super.onResume();
		Intent intent = getIntent(); 
		mtype = intent.getStringExtra("mtype");
		if(mtype==null || mtype.equalsIgnoreCase("null"))
			mtype = "";
		otherusername = intent.getStringExtra("otherusername");
		if(otherusername==null || otherusername.equalsIgnoreCase("null"))
			otherusername = "";
		JIDWithRes = intent.getStringExtra("JIDWithRes");
		if(JIDWithRes==null || JIDWithRes.equalsIgnoreCase("null"))
			JIDWithRes = "";
		from = intent.getStringExtra("mFrom");
		roomname = intent.getStringExtra("roomname");
		if(roomname==null || roomname.equalsIgnoreCase("null"))
			roomname = "";
		
		roomid = intent.getStringExtra("roomid");
		if(roomid==null || roomid.equalsIgnoreCase("null"))
			roomid = "";
		
		if(roomid!=null
				&& !roomid.equalsIgnoreCase("null")
				&& roomid.length()!=0)
			otherusername = roomid;
		
    	nickname = intent.getStringExtra("nickname");
		if(nickname==null || nickname.equalsIgnoreCase("null"))
			nickname = "";
    	name = intent.getStringExtra("name");
		if(name==null || name.equalsIgnoreCase("null"))
			name = "";
    	headimg = intent.getStringExtra("headimg");
		if(headimg==null || headimg.equalsIgnoreCase("null"))
			headimg = "";
    	myheadimg = intent.getStringExtra("myheadimg");
		if(myheadimg==null || myheadimg.equalsIgnoreCase("null"))
			myheadimg = "";
    	myusername = intent.getStringExtra("myusername");
		if(myusername==null || myusername.equalsIgnoreCase("null"))
			myusername = "";
		myjid = intent.getStringExtra("myjid");
		if(myjid==null || myjid.equalsIgnoreCase("null"))
			myjid = "";	
    	if(from!=null 
    			&& !from.equalsIgnoreCase("null") 
    			&& from.length()!=0)
    		try{
    			mFrom = Integer.parseInt(from);
    		}catch(Exception e){
    			mFrom = 0;
    		}
    	mImageFetcher.setExitTasksEarly(false);
		if (!mBinded){
			mBinded = bindService(new Intent(this, BeemService.class), mServConn, BIND_AUTO_CREATE);
		}
    }
    @Override
    protected void onPause() {
		super.onPause();
		mImageFetcher.setExitTasksEarly(true);
		if (mBinded) {
			unbindService(mServConn);
			mBinded = false;
		}
    }
    @Override
    protected void onDestroy() {
		super.onDestroy();
		mImageFetcher.onCancel_RoundImage();
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
		if (mBinded) {
			unbindService(mServConn);
			mBinded = false;
		}
//		this.unregisterReceiver(mReceiver);//原来的网络状态注释掉
		clearAsyncTask();
		mXmppFacade = null;
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
    }
//	private void initData()
//	{
//		data = new ArrayList<HashMap<String,Object>>();
//		
////		HashMap<String,Object> map;
////		Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.empty_photo3);
////		for(int i=0; i < 2; i++){
////			map = new HashMap<String, Object>();
////			map.put(EasyGridView.IMAGE, bmp);
//////			map.put(EasyGridView.TEXT, "娜美");
////			data.add(map);
////		}
//	}
//	@Override
	protected void initViews()
	{
//		allEasyGridView = (AllEasyGridView)findViewById(R.id.my_grid);
//		ImageAdapter adapter = new ImageAdapter(this,false);
//		allEasyGridView.initData(false, data, adapter);
//		allEasyGridView.setHandleGridView(this);
////		allEasyGridView.updateAdapter();
		
		
        mIvUserPhoto = (RoundImageView) findViewById(R.id.reg_photo_iv_userphoto);
		mLayoutSelectPhoto = (LinearLayout) findViewById(R.id.reg_photo_layout_selectphoto);
		mLayoutTakePicture = (LinearLayout) findViewById(R.id.reg_photo_layout_takepicture);
		mLayoutSelectPhoto.setOnClickListener(mOkListener);
		mLayoutTakePicture.setOnClickListener(mOkListener);
	}
//	@Override
//	public void addImage()
//	{
////		Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.empty_photo3);
////		HashMap<String,Object> map = new HashMap<String, Object>();
////		map.put(EasyGridView.IMAGE, bmp);
//////		map.put(EasyGridView.TEXT, "娜美");
////		allEasyGridView.getData().add(map);	
//		if(allEasyGridView.getData().size()<=0)//3->4
//			onCreateDialog(0);
//		else
//			showCustomToast("最多只能添加1张照片!");
//	}
//
//	@Override
//	public void delImage(int position)
//	{
//		allEasyGridView.getData().remove(position);
////		allEasyGridView.updateAdapter();
//		
//		pictures.clear();
//		faners.clear();
//		
//	}
//	@Override
//	public void queryImage(int position)
//	{
//		
//	}
//	@Override
	protected void initEvents() {
		mEetEditer.setOnTouchListener(this);
		mBtnSend.setOnClickListener(this);
		mIvEmote.setOnClickListener(this);
	}
	public void onClick(View v) {
		switch (v.getId()) {
	case R.id.feedprofile_iv_emote:
		mEetEditer.requestFocus();
		if (mInputView.isShown()) {
			showKeyBoard();
		} else {
			hideKeyBoard();
			mInputView.setVisibility(View.VISIBLE);
		}
		break;
	case R.id.feedprofile_btn_send:
		String content = mEetEditer.getText().toString().trim();
		if (TextUtils.isEmpty(content)) {
			showCustomToast("请输入评论内容");
			mEetEditer.requestFocus();
		} else {
			String reply = null;
			if (mEtvEditerTitle.isShown()) {
				reply = mEtvEditerTitle.getText().toString().trim();
			}
			content = TextUtils.isEmpty(reply) ? content : reply + content;
//			FeedComment comment = new FeedComment("测试用户",
//					"nearby_people_other", content, DateUtils.formatDate(
//							AddDynamicsActivity.this,
//							System.currentTimeMillis()));
//			mComments.add(0, comment);
//			mAdapter.notifyDataSetChanged();
			initialAddDynamics(content);
			
		}
		mEtvEditerTitle.setText(null);
		mEtvEditerTitle.setVisibility(View.GONE);
		mEetEditer.setText(null);
		mInputView.setVisibility(View.GONE);
		hideKeyBoard();
		break;
		}
	}
	private void initialAddDynamics(final String memo) {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try{
//					initCurrentAvatar(context);
					StringBuffer str_pictures = new StringBuffer();
					StringBuffer str_faner = new StringBuffer();
					for(int i=0;i<pictures.size();i++){
						str_pictures.append(pictures.get(i)+"|");
					}
				    Iterator iter = faners.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						Object key = entry.getKey();
						Object val = entry.getValue();
						str_faner.append(key+"="+val+"|");
					}
					
					AddDynamics2(memo,str_pictures.toString(),str_faner.toString());
				}catch(Exception e){
					return false;
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (!result) {
					showCustomToast("数据加载失败...");
				} else {
					mHandler.sendEmptyMessage(4);
				}
			}

		});
	} 
	private String roomid = null;
//	public void AddDynamics(String memo,String str_pictures,String str_faner){
//		if(BeemConnectivity.isConnected(getApplicationContext())){
//		    try {
//		    	if(mXmppFacade!=null){
//			    	if (mXmppFacade.getXmppConnectionAdapter()!=null 
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected() 
//			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//			    			&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()){
//			    		String mtype = "0";
//			    		String dynamicid = "";
//			    		String username = StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID());//个人动态
//			    		if(roomid!=null
//			    				&& !roomid.equalsIgnoreCase("null")
//			    				&& roomid.length()!=0)
//			    			username = roomid;//群动态
//			    		String otherusername = "";
//			    		String longitude = String.valueOf(SpiceApplication.getInstance().mLongitude);
//			    		String latitude = String.valueOf(SpiceApplication.getInstance().mLatitude);
////			    		String memo;
////			    		String str_pictures;
////			    		String str_faner;
//			    		String time = com.spice.im.utils.TextUtils.dateToMillis(new Date());
//			    		String geolocation = SpiceApplication.getInstance().mGpsAddr;
//			    		int startIndex = 0;
//			    		int numResults = 100;
//			    		mXmppFacade.getDynamicsItems(mtype,
//			    	    		dynamicid,
//			    	    		username,
//			    	    		otherusername,
//			    	    		longitude,
//			    	    		latitude,
//			    	    		memo,
//			    	    		str_pictures,
//			    	    		str_faner,
//			    	    		time,
//			    	    		geolocation,
//			    	    		startIndex,
//			    	    		numResults);
//			    		errorType = 5;
//			    	}else
//			    		errorType = 1;
//		    	}else
//		    		errorType = 2;
//		    }catch (RemoteException e) {
//		    	errorType = 3;
//		    	e.printStackTrace();
//		    	
//		    } catch (Exception e){
//		    	errorType = 3;
//		    	e.printStackTrace();
//		    }
//		}else{
//	    	errorType = 4;
//	    }
//	}
	
	
	
    private boolean AddDynamics2(String memo,String str_pictures,String str_faner){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    		Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
//			    	if(mtype==null 
//		    				|| mtype.equalsIgnoreCase("null")
//		    				|| mtype.length()==0)
			    		mtype = "0";
			    		String dynamicid = "";
			    		String username = StringUtils.parseName(mXmppFacade.getXmppConnectionAdapter().getJID());//个人动态
			    		if(roomid!=null
			    				&& !roomid.equalsIgnoreCase("null")
			    				&& roomid.length()!=0)
			    			username = roomid;//群动态
			    		String otherusername = "";
			    		String longitude = String.valueOf(SpiceApplication.getInstance().mLongitude);
			    		String latitude = String.valueOf(SpiceApplication.getInstance().mLatitude);
//			    		String memo;
//			    		String str_pictures;
//			    		String str_faner;
			    		String time = com.spice.im.utils.TextUtils.dateToMillis(new Date());
			    		String geolocation = SpiceApplication.getInstance().mGpsAddr;
			    		int startIndex = 0;
			    		int numResults = 100;
		    		
		    	    DynamicsIQ reqXML = new DynamicsIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setMtype(mtype);
		            reqXML.setDynamicid(dynamicid);
		            reqXML.setUsername(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            reqXML.setOtherusername(otherusername);
		            reqXML.setLongitude(longitude);
		            reqXML.setLatitude(latitude);
		            reqXML.setMemo(memo);
		            reqXML.setPictures(str_pictures);
		            reqXML.setFaner(str_faner);
		            reqXML.setTime(time);
		            reqXML.setGeolocation(geolocation);
		            reqXML.setRadius(5000*1000+"");
		            reqXML.setStartIndex(startIndex+"");
		            reqXML.setNumResults(numResults+"");
		            
		            
		            
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		            String login = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,login);
//		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+username(uid)+time 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+time;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "dynamicsiq"; 
		    		String namespace = "com:stb:dynamicsiq";
		    		DynamicsIQResponseProvider provider = new DynamicsIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "dynamicsiq", "com:stb:dynamicsiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof DynamicsIQResponse) {
		                	final DynamicsIQResponse dynamicsIQResponse = (DynamicsIQResponse) rt;
	
		                    if (dynamicsIQResponse.getChildElementXML().contains(
		                            "com:stb:dynamicsiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = dynamicsIQResponse.getId();
		                        String Apikey = dynamicsIQResponse.getApikey();
//		                        try{
//		                        	CTTotal = Integer.parseInt(dynamicsIQResponse.getCttotal());
//		                        	totalnumber = Integer.parseInt(dynamicsIQResponse.getTotalnumber());
//		                        	pageCount = CTTotal%numberresult==0? CTTotal/numberresult-1 : CTTotal/numberresult;
//		                        }catch(Exception e){
//		                        	CTTotal = 0;
//		                        	totalnumber = 0;
//		                        }
//		                        results = dynamicsIQResponse.getDynamics();
//					    		if(results!=null && results.size()!=0){
//					    			errorType = 5;
//					    			for(int i=0;i<results.size();i++){
//					    				dynamicsItem = (DynamicsItem)results.get(i);
//					    				feed = new Feed(dynamicsItem.getId()+"","",dynamicsItem.getTime(), 
//					    						dynamicsItem.getMemo(), 
//					    						dynamicsItem.getPictures(),
//					    						dynamicsItem.getFaner(), 
//					    						dynamicsItem.getDistance(),
//												3,//commentCount
//												dynamicsItem.getEmail(),
//												dynamicsItem.getName(),
//												dynamicsItem.getUser_id());
//					    				
////					    				mFeeds.add(feed);
//					    				mFeeds_temp.add(feed);
//					    			}
//					    			return true;
//					    		}else{
//					    			if(results!=null && results.size()==0)
//					    				errorType = 0;
//					    			else
//					    				errorType = 6;
//					    		}
		                        String retcode = dynamicsIQResponse.getRetcode();
		                        memo = dynamicsIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 5;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 6;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
	private String[] errorMsg = new String[]{"没有相关记录.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"",
			"请求异常,稍候重试!"};
	private int errorType = 5;			
	@Override
	public boolean onTouch(View v, MotionEvent event) {

		if (v.getId() == R.id.feedprofile_eet_editer) {
			showKeyBoard();
		}
		return false;
	}
	private void showKeyBoard() {
		if (mInputView.isShown()) {
			mInputView.setVisibility(View.GONE);
		}
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
				.showSoftInput(mEetEditer, 0);
	}

	private void hideKeyBoard() {
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(AddDynamicsActivity.this
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	private int mFrom = 0;
	private String from = "";
	private Intent intent;
	private String roomname = "";
	private String nickname = "";
	private String name = "";
	private String headimg = "";
	private String myheadimg = "";
	private String myusername = "";
	private String otherusername = "";
	private String JIDWithRes = "";
	private String myjid = "";
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
			//OtherFeedListActivity.class mFrom = 1
			//ProfileActivity.class mFrom = 2
			switch(mFrom){
			case 1:
				intent = new Intent(AddDynamicsActivity.this, OtherFeedListActivity.class);
	        	intent.putExtra("otherusername", otherusername);
	        	intent.putExtra("JIDWithRes", otherusername);
	        	intent.putExtra("roomname", roomname);
	        	intent.putExtra("nickname", nickname);
	        	intent.putExtra("name", name);
	        	intent.putExtra("headimg", headimg);
	        	intent.putExtra("myheadimg", myheadimg);
	        	intent.putExtra("myusername", myusername);
	        	intent.putExtra("myjid", myjid);
	        	intent.putExtra("mtype", mtype);
	        	startActivity(intent);
	        	break;
			case 2:
	        	intent = new Intent(AddDynamicsActivity.this, PreferenceActivity.class);
	        	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	            startActivity(intent);
	            break;
	        default:
	        	intent = new Intent(AddDynamicsActivity.this, ContactFrameActivity.class);//ContactListPullRefListActivity
	        	startActivity(intent);
	        	break;
			}
			AddDynamicsActivity.this.finish();

		}
	}
	
//    public Dialog onCreateDialog(int id) {
//		mPopupWindow
//		.showViewTopCenter(findViewById(R.id.layout_right));
//		return null;
//    }
//	public void initPopupWindow() {
//		mPopupWindow = new SelectPicPopupWindow(this,"","",this);
//		mPopupWindow.setOnSubmitClickListener(new SelectPicPopupWindow.onSubmitClickListener() {
//
//			@Override
//			public void onClick() {
//			}
//		});
//		mPopupWindow.setOnDismissListener(new OnDismissListener() {
//
//			@Override
//			public void onDismiss() {
//			}
//		});
//	}
//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        if (mCurrentPhotoFile != null) {
//            outState.putString(KEY_CURRENT_PHOTO_FILE, mCurrentPhotoFile.toString());
//        }
//        super.onSaveInstanceState(outState);
//    }
//    private String fileName = null;
//    @Override
//    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//    	fileName = savedInstanceState.getString(KEY_CURRENT_PHOTO_FILE);
//        if (fileName != null) {
//        	mCurrentPhotoFile = new File(fileName);
//        }
//        super.onRestoreInstanceState(savedInstanceState);
//    }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data1) {
//    	
//    	super.onActivityResult(requestCode, resultCode, data1);
//    	Log.w(TAG, "20130814ManagermentActivity onActivityResult() requestCode="+requestCode);
//    	  // Ignore failed requests
//          if (resultCode != RESULT_OK) return;
//
//          switch (requestCode) {
//              case PHOTO_PICKED_WITH_DATA://从手机相片库中选择照片，直接返回本地相册照片路径        	  
//  				if (data1.getData() == null) {
//					return;
//				}
//				if (!FileUtils.isSdcardExist()) {
//					showCustomToast("SD卡不可用,请检查");
//					return;
//				}
//				Uri uri = data1.getData();
//				String[] proj = { MediaStore.Images.Media.DATA };
//				Cursor cursor = managedQuery(uri, proj, null, null, null);
//				if (cursor != null) {
//					int column_index = cursor
//							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//					if (cursor.getCount() > 0 && cursor.moveToFirst()) {
//						path = cursor.getString(column_index);
//						Bitmap bitmap = BitmapFactory.decodeFile(path);
//						if (PhotoUtils.bitmapIsLarge(bitmap)) {
//							PhotoUtils.cropPhoto(this, this, path);
//						} else {
//							if(bitmap!=null){
////								mangerFragment.imageAdapter.add(path);
//								map = new HashMap<String, Object>();
//								map.put(EasyGridView.IMAGE, new HeadImg(path));
////								map.put(EasyGridView.TEXT, "娜美");
////								data.add(map);
//								allEasyGridView.getData().add(map);	
//								allEasyGridView.updateAdapter();
//								if(roomid!=null
//					    				&& !roomid.equalsIgnoreCase("null")
//					    				&& roomid.length()!=0)
//									startUpload(path,roomid,"");
//								else
//								startUpload(path,jid,"");
//							}
//						}
//					}
//				}            	  
//            	  
//                  break;
//
//              case CAMERA_WITH_DATA://拍照
//	  				path = getMCurrentPhotoFile().getAbsolutePath();
//					Bitmap bitmap = BitmapFactory.decodeFile(path);
//					if (PhotoUtils.bitmapIsLarge(bitmap)) {
//						PhotoUtils.cropPhoto(this, this, path);
//					} else {
//						if(bitmap!=null){
//							map = new HashMap<String, Object>();
//							map.put(EasyGridView.IMAGE, new HeadImg(path));
////							map.put(EasyGridView.TEXT, "娜美");
////							data.add(map);
//							allEasyGridView.getData().add(map);	
//							allEasyGridView.updateAdapter();
//							if(roomid!=null
//				    				&& !roomid.equalsIgnoreCase("null")
//				    				&& roomid.length()!=0)
//								startUpload(path,roomid,"");
//							else
//							startUpload(path,jid,"");
//						}
//					}
//                  break;
////              case PHOTO_PICKED_WITH_DATA_AFTER_TAKEPHOTO:
////            	  mangerFragment.imageAdapter.add(mangerFragment.mCurrentPhotoFile.getAbsolutePath());
////            	  break;
//      		case PhotoUtils.INTENT_REQUEST_CODE_CROP:
//    			if (resultCode == RESULT_OK) {
//    				path = data1.getStringExtra("path");
//    				fanermark = data1.getStringExtra("fanermark");
//    				if(fanermark!=null){
//    					Log.e("※※※※※范儿标签数据20140825范儿标签数据※※※※※", "※※范儿标签数据"+fanermark);
//    				}
//    				if (path != null) {
//    					bitmap = BitmapFactory.decodeFile(path);
//    					if (bitmap != null) {
//    						if(bitmap!=null){
////    							mangerFragment.imageAdapter.add(path);
//								map = new HashMap<String, Object>();
//								map.put(EasyGridView.IMAGE, new HeadImg(path));
////								map.put(EasyGridView.TEXT, "娜美");
////								data.add(map);
//								allEasyGridView.getData().add(map);	
//								allEasyGridView.updateAdapter();
//								if(roomid!=null
//					    				&& !roomid.equalsIgnoreCase("null")
//					    				&& roomid.length()!=0)
//									startUpload(path,roomid,"");
//								else
//    							startUpload(path,jid,"");
//    						}
//    					}
//    				}
//    			}
//    			break;                  
//  		    default:
//  		    	Log.w(TAG, "20130815onActivityResult : invalid request code");
//
//          }
//    }
//	public File mCurrentPhotoFile;
//	public File getMCurrentPhotoFile(){
//		mCurrentPhotoFile = new File(mPopupWindow.getTakePicturePath()); 
//		return mCurrentPhotoFile;
//	}
//	private static final String KEY_CURRENT_PHOTO_FILE = "currentphotofile";
	protected FlippingLoadingDialog mLoadingDialog;
	private Handler mHandler = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				showLoadingDialog("请稍后,正在设置...0%");
				break;
			case 1:
				showLoadingDialog("请稍后,正在设置..."+msg.arg1+"%");
				break;
			case 2:
				pictures.add(picturename); 
				faners.put(picturename, fanermark); 
				dismissLoadingDialog();
				break;
			case 3:
//				bulidCurrentAvator();
				break;
			case 4:
				pictures.clear();
				faners.clear();
				dismissLoadingDialog();
				if(errorType == 5)
				showCustomToast("提交成功!");
				else
					showCustomToast(errorMsg[errorType]);	
				Intent intent = new Intent(AddDynamicsActivity.this,
						OtherFeedListActivity.class);
//				intent.putExtra("entity_profile", mProfile);
//				intent.putExtra("entity_people", mPeople);
				if(roomid!=null
						&& !roomid.equalsIgnoreCase("null")
						&& roomid.length()!=0)
					intent.putExtra("otherusername", roomid);	
				else
				intent.putExtra("otherusername", CurrentUid);//StringUtils.parseName(ui.getJid())
				intent.putExtra("myjid", CurrentUid);
				intent.putExtra("mFrom", "1");
//				intent.putExtra("mtype", mtype);
				startActivity(intent);
				AddDynamicsActivity.this.finish();
				break;
			default:
				break;
			}
		}
	};
	
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
//	private HttpUtils http;
//	private HttpHandler handler;
	String path = "";
	String picturename = "";
	String fanermark = "";
	
	private ArrayList pictures = new ArrayList();
	private HashMap faners = new HashMap();//key=picture.name value=faner
//    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
//    	http = new HttpUtils();
//    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
//    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
//                    @Override  
//                    public void onStart() {  
////                      msgTextview.setText("conn...");  
//                      mHandler.sendEmptyMessage(0);
//                    }  
//                    @Override  
//                    public void onLoading(long total, long current,boolean isUploading) {  
////                        if (isUploading) {  
////                          msgTextview.setText("upload: " + current + "/"+ total);  
////                        } else {  
////                          msgTextview.setText("reply: " + current + "/"+ total);  
////                        }  
//    					android.os.Message message = mHandler.obtainMessage();
////    					message.arg1 = (int) (current);
//    					message.arg1 = (int) (current*100/total);
//    					message.what = 1;
//    		//								message.sendToTarget();
//    					mHandler.sendMessage(message);
//                    }  
//                    public void onSuccess(ResponseInfo<String> responseInfo) { 
//                    	//statuscode == 200
////                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
//                    	mHandler.sendEmptyMessage(2);
////        				mHandler.sendEmptyMessage(0);
////                    	if(path!=null && path.length()!=0 && !path.equalsIgnoreCase("null"))
////	                    	try{
////	                    		mXmppFacade.getXmppConnectionAdapter().saveUserVCardField("imgpath", path.substring(path.lastIndexOf("/")+1));
////	                    	}catch(RemoteException e){
////	                    		e.printStackTrace();
////	                    	}
//                    }  
//                    public void onFailure(HttpException error, String msg) {  
////                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
//                    	Log.e("※※※※※20140301※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
//                    	mHandler.sendEmptyMessage(2);
////        				mHandler.sendEmptyMessage(0);
////                    	if(path!=null && path.length()!=0 && !path.equalsIgnoreCase("null"))
////                        	try{
////                        		mXmppFacade.getXmppConnectionAdapter().saveUserVCardField("imgpath", path.substring(path.lastIndexOf("/")+1));
////    	                    }catch(RemoteException e){
////                        		e.printStackTrace();
////                        	}
//                    }  
//                });  
//        
//    } 
//    
//    public void startUpload(String mPicPath,String fromAccount,String toAccount){
//        final File file = new File(mPicPath);  
//        
//        if (file != null) {  
//        	picturename = file.getName();
////            String request = UploadUtil.uploadFile(file, requestURL);  
////            String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
//        	String uploadHost = XmppConnectionAdapter.uploadHost;
////            RequestParams params=new RequestParams();  
//////            params.addBodyParameter("msg",imgtxt.getText().toString());   
////            params.addBodyParameter(picPath.replace("/", ""), file);   
////            uploadMethod(params,uploadHost);
//////            uploadImage.setText(request);  
//            RequestParams params = new RequestParams();
////            params.addHeader("name", "value");
////            params.addQueryStringParameter("name", "value");
//            params.addQueryStringParameter("fromAccount", fromAccount);
//            params.addQueryStringParameter("toAccount", toAccount);
//            params.addQueryStringParameter("sendType", "img");
//            params.addQueryStringParameter("sendSize", "0");
//            // 只包含字符串参数时默认使用BodyParamsEntity，
//            // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
////            params.addBodyParameter("fromAccount", fromAccount);
////            params.addBodyParameter("toAccount", toAccount);
////            params.addBodyParameter("sendType", "audio");
////            params.addBodyParameter("sendSize", (int) mRecord_Time+"");
//
//            // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
//            // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
//            // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
//            // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
//            // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
////            BodyParamsEntity bpe = new BodyParamsEntity();
////            bpe.addParameter("fromAccount", fromAccount);
////            bpe.addParameter("toAccount", toAccount);
////            bpe.addParameter("sendType", "audio");
////            bpe.addParameter("sendSize", (int) mRecord_Time+"");
////            params.setBodyEntity(bpe);
//            params.addBodyParameter("file", file);
//            uploadMethod(params,uploadHost);
//            
//        } 
//    }
    private class BeemServiceConnection implements ServiceConnection {
    	private Context mContext;
		/**
		 * constructor.
		 */
		public BeemServiceConnection(Context context) {
			mContext = context;
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    mBinded = true;//20130804 added by allen
		    try{
		    	mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(AddDynamicsActivity.this);//网络状态相关
		    	CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		    	jid = CurrentUid;
		    	}catch(Exception e){}
//			displayCurrentAvatar(mContext);
		    }
		}
	
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
			mBinded = false;
		    mXmppFacade = null;
		}
    }
//	private void displayCurrentAvatar(final Context context) {
//
//		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {
//
//			@Override
//			protected void onPreExecute() {
//				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
//			}
//
//			@Override
//			protected Boolean doInBackground(Void... params) {
//				try{
//					initCurrentAvatar(context);
//				}catch(Exception e){
//					return false;
//				}
//				return true;
//			}
//
//			@Override
//			protected void onPostExecute(Boolean result) {
//				super.onPostExecute(result);
//				dismissLoadingDialog();
//				if (!result) {
//					showCustomToast("数据加载失败...");
//				} else {
//					mHandler.sendEmptyMessage(3);
//				}
//			}
//
//		});
//	} 
//    private void initCurrentAvatar(Context context) throws Exception{
//		try {
//			if(mXmppFacade!=null){
//				ui = mXmppFacade.getUserInfo();
//			}
//		    Log.d(TAG, "20130815User info : (ui == null)= " + (ui == null));
//		    
//		    if(ui != null){
//		    	jid = ui.getJid();
//		    }
//		} catch (RemoteException e) {
//		    Log.e(TAG, "20130815Error while displaying current avatar1", e);
//		    throw e;
//		} catch (Exception e){
//			Log.e(TAG, "20130815Error while displaying current avatar2", e);
//			throw e;
//		}
//    }
    
    
    /**
     * Listener.
     */
    private class OkListener implements OnClickListener {
	
		/**
		 * Constructor.
		 */
		public OkListener() { }
	
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			//网络设置
	        case R.id.net_status_bar_btn:
				setNetworkMethod(mContext);
			break;
				case R.id.reg_photo_layout_selectphoto:
					GalleryHelper.openGallerySingle(AddDynamicsActivity.this, true, new GalleryImageLoader());
					break;
	
				case R.id.reg_photo_layout_takepicture:
					takePhotoAction();
				break;
			}
	
		}
    };
    
	public void setUserPhoto(Bitmap bitmap) {
		if (bitmap != null) {
			mUserPhoto = bitmap;
			mIvUserPhoto.setImageBitmap(mUserPhoto);
			return;
		}
		showCustomToast("未获取到图片");
		mUserPhoto = null;
		mIvUserPhoto.setImageResource(R.drawable.ic_common_def_header);
	}
	
	public static final int INTENT_REQUEST_CODE_FANER = 9;
	/**
	 * 图片添加标注faner
	 * 
	 * @param context
	 * @param activity
	 * @param path
	 *            图片路径
	 */
	public static void cropPhoto(Context context, Activity activity, String path) {
		Intent intent = new Intent(context, ImageFactoryActivity.class);
		if (path != null) {
			intent.putExtra("path", path);
			intent.putExtra(ImageFactoryActivity.TYPE,
					ImageFactoryActivity.FANER);
		}
		activity.startActivityForResult(intent, INTENT_REQUEST_CODE_FANER);
	}
	
	Uri uri = null;
	//利用requestCode区别开不同的返回结果
	//resultCode参数对应于子模块中setResut(int resultCode, Intent intent)函数中的resultCode值，用于区别不同的返回结果（如请求正常、请求异常等）
	//对应流程：
	//母模块startActivityForResult--触发子模块，根据不同执行结果设定resucode值，最后执行setResut并返回到木模块--母模块触发onActivityResult，根据requestcode参数区分不同子模块。
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==2 && resultCode==2 && data!=null){
        	String filepath = data.getStringExtra("filepath");
        	Toast.makeText(AddDynamicsActivity.this, "filepath="+filepath, Toast.LENGTH_LONG).show();
			if(filepath.length() > 0){
//				sendFile(filepath);//P2P send file
				File file = new File(filepath);
				if (file.exists() && file.canRead()) {
//					sendOfflineFile(filepath,"file");//send offline file via agent file server 
					cropPhoto(this, this, filepath);			    
				} else {
					Toast.makeText(AddDynamicsActivity.this, "file not exists", Toast.LENGTH_LONG).show();
				}
			}
        }
        else if ( requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

                if ( photoInfo != null ) {
//                    ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                    uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                    Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
//                    sendOfflineFile(photoInfo.getPhotoPath(),"img");
                    cropPhoto(this, this, photoInfo.getPhotoPath());
                }

                if ( photoInfoList != null ) {
                    Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
                }
            }
        }
        else if ( requestCode == GalleryHelper.TAKE_REQUEST_CODE ) {
            if (resultCode == RESULT_OK && mTakePhotoUri != null) {
                final String path = mTakePhotoUri.getPath();
                final PhotoInfo info = new PhotoInfo();
                info.setPhotoPath(path);
//                updateGallery(path);

                final int degress = BitmapUtils.getDegress(path);
                if (degress != 0) {
                    new com.beem.push.utils.AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            toast("请稍等…");
                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Bitmap bitmap = rotateBitmap(path, degress);
                                saveRotateBitmap(bitmap, path);
                                bitmap.recycle();
                            } catch (Exception e) {
                                Logger.e(e);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void voids) {
                            super.onPostExecute(voids);
//                            takeResult(info);
                            toPhotoCrop(info);
                        }
                    }.execute();
                } else {
//                    takeResult(info);
                	toPhotoCrop(info);
                }
            } else {
                toast("拍照失败");
            }
        } else if ( requestCode == GalleryHelper.CROP_REQUEST_CODE) {
            if ( resultCode == GalleryHelper.CROP_SUCCESS ) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                resultSingle(photoInfo);
            }
        } else if ( requestCode == GalleryHelper.GALLERY_RESULT_SUCCESS ) {
            PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
            List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

            if ( photoInfo != null ) {
//                ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
                uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
                Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
//                sendOfflineFile(photoInfo.getPhotoPath(),"img");
                cropPhoto(this, this, photoInfo.getPhotoPath());
            }

            if ( photoInfoList != null ) {
                Toast.makeText(this, "选择了" + photoInfoList.size() + "张", Toast.LENGTH_SHORT).show();
            }
        } else if ( requestCode == INTENT_REQUEST_CODE_FANER ) {
			if (resultCode == RESULT_OK) {
				path = data.getStringExtra("path");
				fanermark = data.getStringExtra("fanermark");
				if(fanermark!=null){
					Log.e("※※※※※范儿标签数据20140825范儿标签数据※※※※※", "※※范儿标签数据"+fanermark);
				}
				if (path != null) {
					sendOfflineFile(path,"img");
				}
			}
        }
    }
    
  //recodeTime
    String transformfilepath = "";
    String transformfiletype = "";
    private void sendOfflineFile(String filepath,String type) {
		
    	transformfilepath = filepath;
    	transformfiletype = type;
    	
		try{
    		File file2 = new File(transformfilepath);
    		if(file2.exists()){
    			picturename = file2.getName();//
    			Bitmap bitmap = BitmapFactory.decodeFile(transformfilepath);
//    			setUserPhoto(bitmap);
    			upload(transformfilepath,"9999");
    			
    		}
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    
    /**
     * 拍照
     */
    String mPhotoTargetFolder = null;
    Uri mTakePhotoUri = null;
    protected void takePhotoAction() {

        if (!DeviceUtils.existSDCard()) {
//            toast("没有SD卡不能拍照呢~");
        	Toast.makeText(this, "没有SD卡不能拍照呢~", Toast.LENGTH_SHORT).show();
            return;
        }

        File takePhotoFolder = null;
        if (cn.finalteam.toolsfinal.StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = cn.finalteam.toolsfinal.FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
    }
    protected int mScreenWidth = 720;
    protected int mScreenHeight = 1280;
    protected Bitmap rotateBitmap(String path, int degress) {
        try {
            Bitmap bitmap = BitmapUtils.compressBitmap(path, mScreenWidth / 4, mScreenHeight / 4);
            bitmap = BitmapUtils.rotateBitmap(bitmap, degress);
            return bitmap;
        } catch (Exception e) {
            Logger.e(e);
        }

        return null;
    }

    protected void saveRotateBitmap(Bitmap bitmap, String path) {
        //保存
        BitmapUtils.saveBitmap(bitmap, new File(path));
        //修改数据库
        ContentValues cv = new ContentValues();
        cv.put("orientation", 0);
        ContentResolver cr = getContentResolver();
        String where = new String(MediaStore.Images.Media.DATA + "='" + cn.finalteam.toolsfinal.StringUtils.sqliteEscape(path) +"'");
        cr.update(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv, where, null);
    }
    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    protected void resultSingle(PhotoInfo photoInfo) {
//        Intent intent = getIntent();
//        if (intent == null) {
//            intent = new Intent();
//        }
//        intent.putExtra(GalleryHelper.RESULT_DATA, photoInfo);
////        setResult(GalleryHelper.GALLERY_RESULT_SUCCESS, intent);
////        finish();
//        startActivityForResult(intent, GalleryHelper.GALLERY_RESULT_SUCCESS);
    	
        if ( photoInfo != null ) {
//          ImageLoader.getInstance().displayImage("file:/" + photoInfo.getPhotoPath(), mIvResult);
          uri = Uri.parse("file:/" + photoInfo.getPhotoPath());
          Toast.makeText(this, "选择了照片路径:" + photoInfo.getPhotoPath(), Toast.LENGTH_SHORT).show();
          sendOfflineFile(photoInfo.getPhotoPath(),"img");
      }
    }
    /**
     * 执行裁剪
     */
    protected void toPhotoCrop(PhotoInfo info) {
        Intent intent = new Intent(this, PhotoCropActivity.class);
        intent.putExtra(PhotoCropActivity.PHOTO_INFO, info);
        startActivityForResult(intent, GalleryHelper.CROP_REQUEST_CODE);
    }
    
    
    public void upload(String mPicPath,String fromAccount){
    	try{
            final File file = new File(mPicPath);  
            
            if (file != null) {  
//                String request = UploadUtil.uploadFile(file, requestURL);  
//                String uploadHost="http://10.0.2.2:9090/plugins/offlinefiletransfer/offlinefiletransfer";  
            	String uploadHost = XmppConnectionAdapter.uploadHost.replace("OfflinefiletransferServlet", "UploadHeadServlet");
            	uploadHost = "http://10.0.2.2:8080/thinkis/maps/Resource/uploadFeed.jsp";
            	uploadHost = XmppConnectionAdapter.downloadPrefix + "/maps/Resource/uploadFeed.jsp";
//                RequestParams params=new RequestParams();  
////                params.addBodyParameter("msg",imgtxt.getText().toString());   
//                params.addBodyParameter(picPath.replace("/", ""), file);   
//                uploadMethod(params,uploadHost);
////                uploadImage.setText(request);  
                RequestParams params = new RequestParams();
//                params.addHeader("name", "value");
//                params.addHeader(HttpUtils.HEADER_ACCEPT_ENCODING, HttpUtils.ENCODING_GZIP);
                params.addHeader("Accept-Encoding", "gzip");
//                params.addQueryStringParameter("name", "value");
                params.addQueryStringParameter("fromAccount", CurrentUid);//代表存储目录fromAccount
//                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
//        	    String uid = settings.getString("uidStr", "");
        	    params.addQueryStringParameter("uidStr", CurrentUid);
                params.addQueryStringParameter("sendType", "img");
                params.addQueryStringParameter("sendSize", "0");
                // 只包含字符串参数时默认使用BodyParamsEntity，
                // 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
//                params.addBodyParameter("fromAccount", fromAccount);
//                params.addBodyParameter("toAccount", toAccount);
//                params.addBodyParameter("sendType", "audio");
//                params.addBodyParameter("sendSize", (int) mRecord_Time+"");

                // 加入文件参数后默认使用MultipartEntity（"multipart/form-data"），
                // 如需"multipart/related"，xUtils中提供的MultipartEntity支持设置subType为"related"。
                // 使用params.setBodyEntity(httpEntity)可设置更多类型的HttpEntity（如：
                // MultipartEntity,BodyParamsEntity,FileUploadEntity,InputStreamUploadEntity,StringEntity）。
                // 例如发送json参数：params.setBodyEntity(new StringEntity(jsonStr,charset));
//                BodyParamsEntity bpe = new BodyParamsEntity();
//                bpe.addParameter("fromAccount", fromAccount);
//                bpe.addParameter("toAccount", toAccount);
//                bpe.addParameter("sendType", "audio");
//                bpe.addParameter("sendSize", (int) mRecord_Time+"");
//                params.setBodyEntity(bpe);
                params.addBodyParameter("file", file);
                uploadMethod(params,uploadHost);
                
            }  
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
	private HttpUtils http;
	private HttpHandler handler;
	
    //上传照片start
    public  void uploadMethod(final RequestParams params,final String uploadHost) {  
    	http = new HttpUtils();
    	http.configCurrentHttpCacheExpiry(1000 * 10); // 设置缓存10秒，10秒内直接返回上次成功请求的结果。
    	
    	handler = http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {  
                    @Override  
                    public void onStart() {  
//                      msgTextview.setText("conn...");  
                      mHandler2.sendEmptyMessage(4);
                    }  
                    @Override  
                    public void onLoading(long total, long current,boolean isUploading) {  
//                        if (isUploading) {  
//                          msgTextview.setText("upload: " + current + "/"+ total);  
//                        } else {  
//                          msgTextview.setText("reply: " + current + "/"+ total);  
//                        }  
    					android.os.Message message = mHandler2.obtainMessage();
//    					message.arg1 = (int) (current*100/total);
    					message.arg1 = 80;//gzip 后 total为0
    					message.what = 1;
    		//								message.sendToTarget();
    					mHandler2.sendMessage(message);
                    }  
                    public void onSuccess(ResponseInfo<String> responseInfo) { 
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传成功"+responseInfo.statusCode+";reply: " + responseInfo.result);
                    	//statuscode == 200
//                      msgTextview.setText("statuscode:"+responseInfo.statusCode+";reply: " + responseInfo.result); 
                    	
                    	mHandler2.sendEmptyMessage(2);
                    }  
                    public void onFailure(HttpException error, String msg) {  
//                      msgTextview.setText(error.getExceptionCode() + ":" + msg);  
                    	Log.e("※※※※※####20140806####※※※※※", "※※上传失败"+error.getExceptionCode() + ":" + msg);
                    	mHandler2.sendEmptyMessage(3);
                    }  
                });  
        
    } 
    
	Handler mHandler2 = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if(errorType==5){

				}else{
//					Toast.makeText(GpsSearchResPullRefListActivity.this,errorMsg[errorType], 1000).show();
					showCustomToast(errorMsg[errorType]);
				}
				break;
			case 1:
				
				progress.setText(msg.arg1+"%");//20150831 第三种方法
				bar.setProgress(msg.arg1);//20150831 第三种方法
				break;
			case 2:
				pictures.add(picturename); 
				faners.put(picturename, fanermark); 
				
				progress.setText("100%");//20150831 第三种方法
				bar.setProgress(100);//20150831 第三种方法
				
				creatingProgress.dismiss();
//				transformfilepath = 
//				if(transformfilepath.lastIndexOf("/")!=-1)
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath.substring(transformfilepath.lastIndexOf("/")+1);
//				else
//					transformfilepath = XmppConnectionAdapter.downloadPrefix+"9999"+"/"+transformfilepath;
				if(mIvUserPhoto != null)
					mImageFetcher.loadRoundImage(transformfilepath, mIvUserPhoto,null);
				break;
			case 3:
				progress.setText("上传失败!");
				creatingProgress.dismiss();
				break;
			case 4:
				initialProgressDialog();
				creatingProgress.show();
				break;
			default:
				if(errorType!=5)
					showCustomToast(errorMsg[errorType]);
				break;
			}
		}

	};
    //上传照片end
    
    private  Dialog creatingProgress = null;
	private ProgressBar bar;
	private TextView progress;
	
	public void initialProgressDialog(){
		//创建处理进度条
		creatingProgress= new Dialog(AddDynamicsActivity.this,R.style.Dialog_loading_noDim);
		Window dialogWindow = creatingProgress.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		lp.width = (int) (getResources().getDisplayMetrics().density*240);
		lp.height = (int) (getResources().getDisplayMetrics().density*80);
		lp.gravity = Gravity.CENTER;
		dialogWindow.setAttributes(lp);
		creatingProgress.setCanceledOnTouchOutside(false);//禁用取消按钮
		creatingProgress.setContentView(R.layout.activity_recorder_progress);
		
		progress = (TextView) creatingProgress.findViewById(R.id.recorder_progress_progresstext);
		bar = (ProgressBar) creatingProgress.findViewById(R.id.recorder_progress_progressbar);
	}
	
	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(AddDynamicsActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(AddDynamicsActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	//网络状态 start
			@Override
			public void connectionStatusChanged(int connectedState, String reason) {
				Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
				switch (connectedState) {
				case 0://connectionClosed
					mHandler3.sendEmptyMessage(0);
					break;
				case 1://connectionClosedOnError
//					mConnectErrorView.setVisibility(View.VISIBLE);
//					mNetErrorView.setVisibility(View.VISIBLE);
//					mConnect_status_info.setText("连接异常!");
					mHandler3.sendEmptyMessage(1);
					break;
				case 2://reconnectingIn
//					mNetErrorView.setVisibility(View.VISIBLE);
//					mConnect_status_info.setText("连接中...");
					mHandler3.sendEmptyMessage(2);
					break;
				case 3://reconnectionFailed
//					mNetErrorView.setVisibility(View.VISIBLE);
//					mConnect_status_info.setText("重连失败!");
					mHandler3.sendEmptyMessage(3);
					break;
				case 4://reconnectionSuccessful
//					mNetErrorView.setVisibility(View.GONE);
					mHandler3.sendEmptyMessage(4);

				default:
					break;
				}
			}
			Handler mHandler3 = new Handler() {

				@Override
				public void handleMessage(android.os.Message msg) {
					super.handleMessage(msg);
					switch (msg.what) {
					case 0:
						break;

					case 1:
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("连接异常!");
						break;

					case 2:
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("连接中...");
						break;
					case 3:
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("重连失败!");
						break;
						
					case 4:
						mNetErrorView.setVisibility(View.GONE);
						String udid = "";
						String partnerid = "";
						try{
							udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
							partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
						}catch(Exception e){
							e.printStackTrace();
						}
//						udidTextView.setText("udid="+udid);
//						partneridEditText.setText(partnerid);
//						getContactList();//20141025 added by allen
						break;
					case 5:
						mNetErrorView.setVisibility(View.VISIBLE);
						mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
						break;
					case 6:
						if(mXmppFacade!=null 
//								&& mXmppFacade.getXmppConnectionAdapter()!=null 
//								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//								&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
								&& BeemConnectivity.isConnected(mContext)){
							
						}else{
							mNetErrorView.setVisibility(View.VISIBLE);
							if(BeemConnectivity.isConnected(mContext))
							mConnect_status_info.setText("网络可用,连接中...");
						}
						break;	
					}
				}

			};
			private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
		        @Override
		        public void onReceive(Context context, Intent intent) {
		            String action = intent.getAction();  
		            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
		                Log.d("PoupWindowContactList", "网络状态已经改变");  
//		                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//		                info = connectivityManager.getActiveNetworkInfo();    
//		                if(info != null && info.isAvailable()) {  
//		                    String name = info.getTypeName();  
//		                    Log.d(tag, "当前网络名称：" + name);  
//		                    //doSomething()  
//		                } else {  
//		                    Log.d(tag, "没有可用网络");  
//		                  //doSomething()  
//		                }  
		                if(BeemConnectivity.isConnected(context)){
//		                	mNetErrorView.setVisibility(View.GONE);
//		                	isconnect = 0;
		                	mHandler3.sendEmptyMessage(6);//4
		                }else{
//		                	mNetErrorView.setVisibility(View.VISIBLE);
//		                	isconnect = 1;
		                	mHandler3.sendEmptyMessage(5);
		                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
		                }
		            } 
		        }
			};
			
			private boolean phonestate = false;//false其他， true接起电话或电话进行时 
		    /* 内部class继承PhoneStateListener */
		    public class exPhoneCallListener extends PhoneStateListener
		    {
		        /* 重写onCallStateChanged
		        当状态改变时改变myTextView1的文字及颜色 */
		        public void onCallStateChanged(int state, String incomingNumber)
		        {
		          switch (state)
		          {
		            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
		            case TelephonyManager.CALL_STATE_IDLE:
		            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
		            	if(phonestate){
		            		onPhoneStateResume();
		            	}
		            	phonestate = false;
		              break;
		            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
		            case TelephonyManager.CALL_STATE_OFFHOOK:
		            	Log.e("================20131216 接起电话时================", "接起电话时");
		            	onPhoneStatePause();
		            	phonestate = true;
		              break;
		            /* 电话进来时 :在通话的过程中*/
		            case TelephonyManager.CALL_STATE_RINGING:
//		              getContactPeople(incomingNumber);
		            	Log.e("================20131216 电话进来时================", "电话进来时");
//		            	onBackPressed();
		            	onPhoneStatePause();
		            	phonestate = true;
		              break;
		            default:
		              break;
		          }
		          super.onCallStateChanged(state, incomingNumber);
		        }
		    }
		    
		    protected void onPhoneStatePause() {
//				super.onPause();
		    	try{
//		    		try {
//		    		    if (mRoster != null) {
//		    			mRoster.removeRosterListener(mBeemRosterListener);
//		    			mRoster = null;
//		    		    }
//		    		} catch (RemoteException e) {
//		    		    Log.d("ContactList", "Remote exception", e);
//		    		}
					if (mBinded) {
						getApplicationContext().unbindService(mServConn);
					    mBinded = false;
					}
					mXmppFacade = null;
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
		    }
		    
		    protected void onPhoneStateResume() {
//				super.onResume();
		    	try{
				if (!mBinded){
//				    new Thread()
//				    {
//				        @Override
//				        public void run()
//				        {
				    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//				        }
//				    }.start();		    
				}
				if (mBinded){
//					mImageFetcher.setExitTasksEarly(false);
				}
		    	}catch(Exception e){
		    		e.printStackTrace();
		    	}
		    }
		    
		    /*
		     * 打开设置网络界面
		     * */
		    public static void setNetworkMethod(final Context context){
		        //提示对话框
		        AlertDialog.Builder builder=new AlertDialog.Builder(context);
		        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
		            
		            @Override
		            public void onClick(DialogInterface dialog, int which) {
		                // TODO Auto-generated method stub
		                Intent intent=null;
		                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
		                if(android.os.Build.VERSION.SDK_INT>10){
		                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
		                }else{
		                    intent = new Intent();
		                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
		                    intent.setComponent(component);
		                    intent.setAction("android.intent.action.VIEW");
		                }
		                context.startActivity(intent);
		            }
		        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
		            
		            @Override
		            public void onClick(DialogInterface dialog, int which) {
		                // TODO Auto-generated method stub
		                dialog.dismiss();
		            }
		        }).show();
		    }
			//网络状态 end
}
